from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .models import DeliveryStaff, Delivery
from .serializers import DeliveryStaffSerializer, DeliverySerializer
from utils.permissions import IsAdminOrReadOnly
from utils.response import api_response

class DeliveryStaffViewSet(viewsets.ModelViewSet):
    queryset = DeliveryStaff.objects.all()
    serializer_class = DeliveryStaffSerializer
    permission_classes = [IsAdminOrReadOnly]

class DeliveryViewSet(viewsets.ModelViewSet):
    serializer_class = DeliverySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        if user.is_staff:
            return Delivery.objects.all()
        if hasattr(user, 'deliverystaff'):
            return Delivery.objects.filter(staff=user.deliverystaff)
        return Delivery.objects.filter(order__user=user)

    @action(detail=True, methods=['post'])
    def update_status(self, request, pk=None):
        delivery = self.get_object()
        new_status = request.data.get('status')
        
        if not new_status or new_status not in dict(Delivery.DELIVERY_STATUS):
            return api_response(400, "状态无效")

        # 检查状态转换是否合法
        current_status = delivery.status
        if not self._is_valid_status_transition(current_status, new_status):
            return api_response(400, "状态转换无效")

        delivery.status = new_status
        delivery.save()
        return api_response(data=DeliverySerializer(delivery).data)

    def _is_valid_status_transition(self, current, new):
        # 定义合法的状态转换
        valid_transitions = {
            'assigned': ['picked'],
            'picked': ['delivering'],
            'delivering': ['completed'],
        }
        return new in valid_transitions.get(current, []) 